package com.luboyan.CBillbill.advice;

import com.luboyan.CBillbill.annotation.ApiLimited;
import com.luboyan.CBillbill.exception.ConditionException;
import com.luboyan.CBillbill.dao.user.auth.UserRole;
import com.luboyan.CBillbill.service.user.auth.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
@Order(1)
public class ApiLimitedAdvice {

    @Autowired
    private TokenVerify tokenVerify;

    @Autowired
    private UserRoleService userRoleService;

    @Pointcut("@annotation(com.luboyan.CBillbill.annotation.ApiLimited)")
    public void apiLimitedCheck() {
    }

    @Before("apiLimitedCheck() && @annotation(apiLimited)")
    public void RoleLimited(JoinPoint joinPoint, ApiLimited apiLimited) {
        Long userId = tokenVerify.getCurrentUserId();
        List<UserRole> userRoles = userRoleService.getUserRoleByUserId(userId);
        String[] limitedRoles = apiLimited.limitedRoles();
        Set<String> limitedRolesSet = Arrays.stream(limitedRoles).collect(Collectors.toSet());
        Set<String> userRolesSet = userRoles.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        userRolesSet.retainAll(limitedRolesSet);
        if (!userRolesSet.isEmpty()) {
            throw new ConditionException("权限不足，无法访问！");
        }

    }
}
